﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Security;

namespace eCommerce.DataAccess
{
    public class SiteFunctions
    {
        public static string DateFromToString(DateTime From, DateTime To)
        {
            string datetofromstring = "";
            DayNumberFormatInfo daynumberformat = new DayNumberFormatInfo();
            if (From.Year == To.Year)
            {
                if (From.Month == To.Month)
                {
                    if (From.Day == To.Day)
                    {
                        datetofromstring = FullDateNoTrailingZeroWithSuffix(To);
                    }
                    else
                    {
                        datetofromstring = From.Day + string.Format(daynumberformat, "{0:x}", From) + " - " + FullDateNoTrailingZeroWithSuffix(To);
                    }
                }
                else
                {
                    datetofromstring = From.Day + string.Format(daynumberformat, "{0:x}", From) + " " + From.ToString("MMMM") + " - " + FullDateNoTrailingZeroWithSuffix(To);
                }
            }
            else
            {
                datetofromstring = FullDateNoTrailingZeroWithSuffix(From) + " - " + FullDateNoTrailingZeroWithSuffix(To);
            }
            return datetofromstring;
        }

        public static string FullDateNoTrailingZeroWithSuffix(DateTime d)
        {
            DayNumberFormatInfo daynumberformat = new DayNumberFormatInfo();
            string fulldate = "";
            fulldate = d.Day + string.Format(daynumberformat, "{0:x}", d) + " " + d.ToString("MMMM yyyy");
            return fulldate;
        }

        public static bool ColumnExists(DataTable Table, string ColumnName)
        {
            bool bRet = false;
            foreach (DataColumn col in Table.Columns)
            {
                if (col.ColumnName == ColumnName)
                {
                    bRet = true;
                    break;
                }
            }
            return bRet;
        }

        public static bool CheckMemberAddress(Guid userid)
        {
            eCommerceDataContext dataContext = new eCommerceDataContext();
            var addressExists = (dataContext.AddressUsers.Where(a => a.userid == userid)).FirstOrDefault();
            return addressExists != null;
        }
        public static Guid GetMemberAddressID(Guid userid)
        {
            eCommerceDataContext dataContext = new eCommerceDataContext();
            var memAddressID = (dataContext.AddressUsers.Where(m => m.userid == userid && m.addresstype == 1)).FirstOrDefault();
            if (memAddressID == null) throw new NotImplementedException();
            return memAddressID.addressid;
            
        }
        public static Guid GetMemberDeliveryAddressID(Guid userid)
        {
            eCommerceDataContext dataContext = new eCommerceDataContext();
            var deliveryAddressID = (dataContext.AddressUsers.Where(da => da.userid == userid && da.addresstype == 2)).FirstOrDefault();
            if (deliveryAddressID == null) throw new NotImplementedException();
            return deliveryAddressID.addressid;
        }

        public static int GetCountryID(string countryvalue)
        {
            eCommerceDataContext dataContext = new eCommerceDataContext();
            
                var countryID = (from c in dataContext.Country_Codes
                                where c.Code == countryvalue
                                select c).SingleOrDefault();

            int ccode = countryID.ID;
            return ccode;


        }
        public static void createNewGuid()
        {
            
            {
                bool createdGuid = false;
                while (!createdGuid)
                {
                    using (
                    SqlConnection sqlConn =
                        new SqlConnection(
                            ConfigurationManager.ConnectionStrings["SqlConnectionString"].ConnectionString))
                    {
                        sqlConn.Open();
                        Guid cartid = Guid.NewGuid();
                        SqlCommand sqlcmd = new SqlCommand("custom_getcartidbycartid", sqlConn);
                        sqlcmd.CommandType = CommandType.StoredProcedure;
                        sqlcmd.Parameters.Add(new SqlParameter("@cartid", cartid));
                        SqlDataReader x = sqlcmd.ExecuteReader();
                        if (x.HasRows)
                        {
                            createdGuid = true;
                            insertGuid(cartid);
                        }
                       
                    }
                    
                   
                }
            }
        }

        private static void insertGuid(Guid cartid)
        {
            //using (SqlConnection sqlConn = new SqlConnection(ConfigurationManager.ConnectionStrings["SqlConnectionString"].ConnectionString))
            //{
            //    string sql;
            //    SqlCommand sqlCmd;
            //    sql = "INSERT INTO harrier_x_cart (cartid,cartip) VALUES ('" + cartid + "','" + HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"] + "')";
            //    sqlCmd = new SqlCommand(sql, sqlConn);
            //    sqlConn.Open();
            //    sqlCmd.ExecuteNonQuery();
            //    HttpContext.Current.Response.Cookies["UserSettings"]["Session"] = cartid.ToString();
            //    HttpContext.Current.Response.Cookies["UserSettings"].Expires = DateTime.Now.AddDays(1d);
           // }
        }

        public static String GetText(String title, String subtitle, Int32 maxlength)
        {
            if (title.Trim().Length > maxlength)
            {
                title = HttpContext.Current.Server.HtmlEncode(title.Trim());
            }
            else
            {
                if (title.Trim().Length + subtitle.Trim().Length > maxlength && subtitle.Length > 0)
                {
                    Int32 pos = 0;
                    if (maxlength - title.Trim().Length <= subtitle.Trim().Length)
                    {
                        pos = subtitle.Trim().IndexOf(" ", maxlength - title.Trim().Length);
                        if (pos < 0)
                        {
                            pos = subtitle.Length;
                        }
                    }
                    else
                    {
                        pos = subtitle.Trim().Length;
                    }
                    title = HttpContext.Current.Server.HtmlEncode(title.Trim()) + " <span>" + HttpContext.Current.Server.HtmlEncode(subtitle.Trim().Substring(0, pos).Trim()) + "...</span>";
                }
                else
                {
                    title = HttpContext.Current.Server.HtmlEncode(title.Trim()) + " <span>" + HttpContext.Current.Server.HtmlEncode(subtitle.Trim()) + "</span>";
                }
            }
            return title;
        }

        public static String GetTextBig(String title, String subtitle, String id, Int32 maxlength, String linkbase)
        {
            subtitle = subtitle.Replace("...", "");
            if (title.Trim().Length > maxlength)
            {
                title = "<a href=\"" + linkbase + id + "\">" + HttpContext.Current.Server.HtmlEncode(title.Trim()) + "</a>";
            }
            else
            {
                if (title.Trim().Length + subtitle.Trim().Length > maxlength && subtitle.Trim().Length > 0)
                {
                    Int32 pos = 0;
                    if (maxlength - title.Trim().Length < subtitle.Trim().Length)
                    {
                        pos = subtitle.Trim().IndexOf(" ", maxlength - title.Trim().Length);
                        if (pos < 0)
                        {
                            pos = subtitle.Trim().Length;
                        }
                    }
                    else
                    {
                        pos = subtitle.Trim().Length;
                    }
                    title = "<a href=\"" + linkbase + id + "\">" + HttpContext.Current.Server.HtmlEncode(title.Trim()) + "</a>";
                    if (subtitle.Trim().Length >= pos && pos > 0)
                    {
                        title += " " + HttpContext.Current.Server.HtmlEncode(subtitle.Trim().Substring(0, pos - 1).Trim()) + "...";
                    }
                    title += " <a href=\"" + linkbase + id + "\" class=\"green\">more details</a>";
                }
                else
                {
                    title = "<a href=\"" + linkbase + id + "\">" + HttpContext.Current.Server.HtmlEncode(title.Trim()) + "</a> " + HttpContext.Current.Server.HtmlEncode(subtitle.Trim()) + " <a href=\"" + linkbase + id + "\" class=\"green\">more details</a>";
                }
            }
            return title;
        }

        public static String GetTextBig(String title, String subtitle, String id, Int32 maxlength, Int32 type)
        {
            String linkbase = "Report.aspx?rid=";
            switch (type)
            {
                case 1:
                    linkbase = "Report.aspx?rid=";
                    break;
                case 2:
                    linkbase = "Event.aspx?cid=";
                    break;
            }
            return GetTextBig(title, subtitle, id, maxlength, linkbase);
        }

        public static String GetLinked(String linkbase, String id, String tolink)
        {
            String linked = "<a href=\"" + linkbase + id + "\">" + tolink + "</a>";
            return linked;
        }

        public static String GetLinked(Int32 type, String id, String tolink)
        {
            String linkbase = "Report.aspx?rid=";
            switch (type)
            {
                case 1:
                    linkbase = "Report.aspx?rid=";
                    break;
                case 2:
                    linkbase = "Event.aspx?cid=";
                    break;
            }
            return GetLinked(linkbase, id, tolink);
        }

        public static String FormatPrices(Double gb, Double us)
        {
            CultureInfo ci2 = new CultureInfo("en-GB");
            String format = gb.ToString("c", ci2);
            ci2 = new CultureInfo("en-US");
            format += " (" + us.ToString("c", ci2) + ")";
            return format;
        }

        public static String GetThumbnail(String image, Int32 width, Int32 height, String defaultimg)
        {
            return "Thumbnail.aspx?file=" + HttpContext.Current.Server.UrlEncode(ImagePath(image, defaultimg)) + "&amp;w=" + width + "&amp;h=" + height;
        }

        public static String ImagePath(string aimage, string dimage)
        {
            if (aimage.Length <= 0)
            {
                aimage = dimage;
            }
            aimage = HttpContext.Current.Server.MapPath(aimage);
            if (!File.Exists(aimage))
            {
                aimage = HttpContext.Current.Server.MapPath(dimage);
            }
            return aimage;
        }

        public static String GetImage(String image, String title, Int32 width, Int32 height, String imgbase)
        {
            if (File.Exists(HttpContext.Current.Server.MapPath(imgbase + image.Trim())))
            {
                image = "<img src=\"" + SiteFunctions.GetThumbnail(imgbase + HttpContext.Current.Server.HtmlEncode(image.Trim()), width, height, "x") + "\" alt=\"" + HttpContext.Current.Server.HtmlEncode(title) + "\" />";
            }
            else
            {
                image = "";
            }
            return image;
        }

        public static String GetSearchImage(String image, String title, Int32 width, Int32 height, Int32 type)
        {
            String imgbase = "";
            switch (type)
            {
                case 1:
                    imgbase = "report/img/";
                    break;
                case 2:
                    imgbase = "conference/img/";
                    break;
            }
            if (File.Exists(HttpContext.Current.Server.MapPath(imgbase + image.Trim())))
            {
                image = "<img src=\"" + SiteFunctions.GetThumbnail(imgbase + HttpContext.Current.Server.HtmlEncode(image.Trim()), width, height, "x") + "\" alt=\"" + HttpContext.Current.Server.HtmlEncode(title) + "\" />";
            }
            else
            {
                image = "";
            }
            return image;
        }

        /*public static Boolean TryStrToGuid(String s, out Guid value)
        {
            SqlGuid x = new SqlGuid();
            SqlGuid.Parse()
            try
            {
                value = new Guid(s);
                return true;
            }
            catch (FormatException)
            {
                value = Guid.Empty;
                return false;
            }
        }*/

        public static Boolean CookiesEnabled
        {
            get
            {
                Guid x = Guid.NewGuid();
                HttpContext.Current.Response.Cookies["test"].Value = x.ToString();
                if (HttpContext.Current.Request.Cookies["test"].Value == x.ToString())
                {
                    return false;
                }
                else
                {
                    return true;
                }
            }
        }

        public static void CheckLogin()
        {
            if (!HttpContext.Current.Request.IsAuthenticated)
            {
                string url = "~/Register_Login.aspx?ReturnUrl=" + HttpContext.Current.Server.UrlEncode(HttpContext.Current.Request.ServerVariables["SCRIPT_NAME"]);
                if (HttpContext.Current.Request.ServerVariables["QUERY_STRING"].Trim().Length > 0)
                {
                    url += "?" + HttpContext.Current.Request.ServerVariables["QUERY_STRING"].Trim();
                }
                HttpContext.Current.Response.Redirect(url);
            }
        }

        public static void CheckCart()
        {
            CartDA cartx = new CartDA();
            if (cartx.Total <= 0)
            {
                HttpContext.Current.Response.Redirect("~/");
            }
        }

        public static MembershipUser GetCurrentUser()
        {
            MembershipUser currentUser = Membership.GetUser(HttpContext.Current.User.Identity.Name);
            if (currentUser == null)
            {
                if (HttpContext.Current.Session["newuser"] != null)
                {
                    currentUser = Membership.GetUser(HttpContext.Current.Session["newuser"].ToString());
                }
                else
                {
                    HttpContext.Current.Response.Redirect("~/");
                }
            }
            return currentUser;
        }

        public static String RemoveDoubleSpaces(String s)
        {
            s = s.Trim().Replace("  ", " ");
            while (s.Contains("  "))
            {
                s = s.Replace("  ", " ");
            }
            return s;
        }

    }
}
